package com.kim.rssreader.base;

import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;

import android.os.Handler;
import android.os.Message;

/**
 * 消息管理类
 * 
 * @author KimHuang
 * 
 */
@Deprecated
public class MessageManager {

	static MessageManager self = new MessageManager();

	private MessageManager() {
	}

	static HashMap<Integer, IObserver> observers = new HashMap<Integer, IObserver>();

	public static final MessageManager getInstance() {
		return self;
	}

	/**
	 * 获取消息处理器
	 * 
	 * @return
	 */
	public final Handler getMainHandler() {
		return MAIN_HANDLER;
	}

	/**
	 * 添加观察者
	 * 
	 * @param what
	 * @param observer
	 */
	public final void addObserver(Integer what, Observer observer) {
		IObserver iObserver = observers.get(what);
		if (iObserver == null) {
			iObserver = new IObserver();
			observers.put(what, iObserver);
		}
		iObserver.addObserver(observer);
	}

	/**
	 * 移除观察者
	 * 
	 * @param what
	 * @param observer
	 */
	public final void deleteObserver(Integer what, Observer observer) {
		IObserver iObserver = observers.get(what);
		if (iObserver != null) {
			iObserver.deleteObserver(observer);
		}
	}

	public final void deleteAllObserver(Integer what) {
		observers.remove(what);
	}

	/**
	 * 发送消息
	 * 
	 * @param message
	 */
	public final void sendNotifyMessage(Message message) {
		MAIN_HANDLER.sendMessage(message);
	}

	/**
	 * 延迟发送消息
	 * 
	 * @param message
	 * @param delay
	 */
	public final void sendNotifyMessageDelay(Message message, long delay) {
		MAIN_HANDLER.sendMessageDelayed(message, delay);
	}

	/**
	 * 处理所有消息
	 * 
	 * @param message
	 */
	private static void handleAll(Message message) {
		if (observers.size() == 0) {
			return;
		}
		Integer what = message.what;
		observers.get(what).notifyObservers(message);
	}

	static final Handler MAIN_HANDLER = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			handleAll(msg);
		}

	};

	private final class IObserver extends Observable {

		@Override
		public void notifyObservers() {
			setChanged();
			super.notifyObservers();
		}

		@Override
		public void notifyObservers(Object data) {
			setChanged();
			super.notifyObservers(data);
		}

	}

}
